import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { useThemeStore } from './store/theme'
import { useAuthStore } from './store/auth'
import { useNotificationsStore } from './store/notifications'
import { permission, role } from './utils/permission'
import './utils/tokenManager' // 引入Token管理工具
import './utils/chartCleanup' // 引入Chart清理工具

const app = createApp(App)
app.use(router)
app.use(createPinia())
app.use(ElementPlus)

// 注册权限控制指令
app.directive('permission', permission)
app.directive('role', role)

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 初始化主题
const themeStore = useThemeStore()
themeStore.initTheme()

// 初始化认证状态
const authStore = useAuthStore()
authStore.initAuth()

// 初始化通知状态
const notificationsStore = useNotificationsStore()
notificationsStore.initialize()

// 延迟启动实时通知服务，避免模块加载冲突
setTimeout(async () => {
  try {
    const { default: messageHandler } = await import('./services/notificationHandler')
    
    if (authStore.isAuthenticated) {
      messageHandler.start()
    }
    
    // 监听认证状态变化，启动/停止通知服务
    authStore.$subscribe((mutation, state) => {
      if (state.isAuthenticated) {
        messageHandler.start()
      } else {
        messageHandler.stop()
      }
    })
  } catch (error) {
    console.error('❌ 初始化消息处理器失败:', error)
  }
}, 1000) // 延迟1秒启动

app.mount('#app')
